﻿using System.Windows;
using System.Windows.Controls;
using GalaSoft.MvvmLight.Messaging;
using ProjectWizardManagementv1.Infrastructure.Abstract;
using ProjectWizardManagementv1.ViewModels.Concrete;

namespace ProjectWizardManagementv1.WpfComponents.ComponentClasses
{
    public class ClosableTab : TabItem
    {
        #region Constants
        private const int THICKNESS_TOP = 3;
        private const int THICKNESS_RIGHT = 4;
        private const int THICKNESS_BOTTOM = 0;
        private const int THICKNESS_LEFT = 5;
        #endregion

        #region Members

        private readonly CloseableHeader _closeableHeader;
        private IClosable _closableContent;
        #endregion

        #region Properties
        public IClosable ClosableContent
        {
            get { return _closableContent; }
            set { _closableContent = value;
                this.Content = value;
            }
        }


        public string Title
        {
            set { ((CloseableHeader) this.Header).TabItemTitle.Content = value; }
        }
        #endregion
        public ClosableTab()
        {
            _closeableHeader = new CloseableHeader();
            _closeableHeader.CloseButton.Click += CloseButton_Click;
            _closeableHeader.TabItemTitle.SizeChanged += TabItemTitle_SizeChanged;
            this.Header = _closeableHeader;
        }

        protected override void OnSelected(RoutedEventArgs e)
        {
            base.OnSelected(e);
            ((CloseableHeader)this.Header).CloseButton.Visibility = Visibility.Visible;
        }

        protected override void OnUnselected(RoutedEventArgs e)
        {
            base.OnUnselected(e);
            ((CloseableHeader)this.Header).CloseButton.Visibility = Visibility.Hidden;
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            var tabControl = this.Parent as TabControl;
            ClosableContent.Close();
            this.ClosableContent = null;

            if (tabControl != null)
            {
                tabControl.Items.Remove(this);
            }
        }

        private void  TabItemTitle_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            ((CloseableHeader)this.Header).CloseButton.Margin = new Thickness(
                ((CloseableHeader)this.Header).TabItemTitle.ActualWidth + THICKNESS_LEFT, THICKNESS_TOP, THICKNESS_RIGHT, THICKNESS_BOTTOM);
        }
    }
}
